package com.atguigu.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketMultiThread {

    public static void main(String[] args) {
        //线程, 操作, 资源类
        Ticket ticket = new Ticket();
/*
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                while(Ticket.count > 0){
                    ticket.sale();
                }
            }
        };
        */

        new Thread(()->{ while (ticket.count> 0 ) ticket.sale();}, "A").start();
        new Thread(()->{ while (ticket.count> 0 ) ticket.sale();}, "B").start();
        new Thread(()->{ while (ticket.count> 0 ) ticket.sale();}, "C").start();


    }
}

class Ticket {
    public int count = 50;
    private final Lock lock = new ReentrantLock(true);
    //final 的作用与必要性  防止锁对象被意外修改

/*    public synchronized void sale() {
        if(count <= 0) return;
        System.out.println(Thread.currentThread().getName() + " 线程运行, 票还有:  " + (count--));
    }*/

    public void sale(){
        lock.lock();
        try {
            if (count <= 0) return;
            System.out.println(Thread.currentThread().getName() + " 线程运行, 票还有:  " + (count--));
        }finally {
            lock.unlock();
        }
    }
}